package com.nhncorp.pleiades.master;

import java.io.IOException;

import com.nhncorp.pleiades.conf.PleiadesConfiguration;
import com.nhncorp.pleiades.hadoop.New_RPC;
import com.nhncorp.pleiades.protocol.RemoteAgentProtocol;
import com.nhncorp.pleiades.util.NetworkUtil;


public class AgentInvoker {
  private PleiadesConfiguration conf = new PleiadesConfiguration();
  
  public static void main(String[] args) throws IOException {

    AgentInvoker invoker = new AgentInvoker();
    RemoteAgentProtocol agent = invoker.connectRemoteAgent(args[0]);
    if(args[1].equals("lock")) {
      agent.lock(args[2]);  
    } else if(args[1].equals("release")) {
      agent.release(args[2]);
    } else if(args[1].equals("dumpLock")) {
      System.out.println(agent.dumpLock());
    } else {
      throw new IOException("command argument is not correct");      
    }
  }
  
  private RemoteAgentProtocol connectRemoteAgent(String server) throws IOException {
    RemoteAgentProtocol remoteAgent = null;
    int maxRetry = 10;
    int retry = 0;
    while (retry < maxRetry) {
      try {
        if( remoteAgent == null) {
          remoteAgent = (RemoteAgentProtocol) New_RPC.getProxy(
              RemoteAgentProtocol.class, RemoteAgentProtocol.versionID,
              NetworkUtil.getAddress(server), conf);
        }
        break;
      } catch (Exception e) {
        e.printStackTrace(System.out);
        remoteAgent = null;
        retry++;
        if (retry >= maxRetry) {
          break;
        }
        try {
          Thread.sleep(100);
        } catch (InterruptedException e1) {
          break;
        }
      }
    }
    return remoteAgent;
  }

}
